import { useState, useEffect } from "react";
import { Form, Input, Select, Button, Table, DatePicker, Space, Tag } from "antd";
import type { ColumnsType } from 'antd/es/table';
import { useLocation } from "react-router-dom";
import styles from "./InandoutofStorageQuery.module.css";

const { RangePicker } = DatePicker;

interface InandoutofStorageRecord {
  id: number;
  team: string;
  typeof: string;
  warehouseName: string;
  createTime: string;
  productType: string;
  productSKU: string;
  productName: string;
  num: number;
  shelfNumber: string;
  containerNumber: string;
  inboundordernumber: string;
  outordernumber: string;
  countordernumber: string;
  remark: string;
  proStatus: number;
}

interface QueryParams {
  currentPage: number;
  pageSize: number;
  team?: string;
  typeof?: string;
  warehouseName?: string;
  createTime?: string;
  endTime?: string;
}

interface ApiResponse {
  code: number;
  message: string;
  data: {
    totalCount: number;
    totalPage: number;
    pageData: InandoutofStorageRecord[];
  };
}

const InandoutofStorageQuery: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<InandoutofStorageRecord[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const location = useLocation();

  // 表格列定义
  const columns: ColumnsType<InandoutofStorageRecord> = [
    {
      title: '序号',
      key: 'index',
      width: 60,
      render: (_, __, index) => (currentPage - 1) * pageSize + index + 1,
    },
    {
      title: '团队',
      dataIndex: 'team',
      key: 'team',
      width: 120,
      ellipsis: true,
    },
    {
      title: '类型',
      dataIndex: 'typeof',
      key: 'typeof',
      width: 70,
      render: (type: string) => (
        <Tag color={type === '入库' ? 'green' : 'orange'}>{type}</Tag>
      ),
    },
    {
      title: '仓库',
      dataIndex: 'warehouseName',
      key: 'warehouseName',
      width: 90,
      ellipsis: true,
    },
    {
      title: '时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 100,
      render: (time: string) => time ? new Date(time).toLocaleDateString() : '-',
    },
    {
      title: '产品类型',
      dataIndex: 'productType',
      key: 'productType',
      width: 90,
      ellipsis: true,
    },
    {
      title: '产品SKU',
      dataIndex: 'productSKU',
      key: 'productSKU',
      width: 100,
      ellipsis: true,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName',
      width: 110,
      ellipsis: true,
    },
    {
      title: '数量',
      dataIndex: 'num',
      key: 'num',
      width: 70,
      render: (num: number, record: InandoutofStorageRecord) => (
        <Tag color={record.proStatus === 0 ? 'green' : 'red'}>{num}</Tag>
      ),
    },
    {
      title: '货架号',
      dataIndex: 'shelfNumber',
      key: 'shelfNumber',
      width: 90,
      ellipsis: true,
    },
    {
      title: '箱号',
      dataIndex: 'containerNumber',
      key: 'containerNumber',
      width: 100,
      ellipsis: true,
    },
    {
      title: '入库单号',
      dataIndex: 'inboundordernumber',
      key: 'inboundordernumber',
      width: 120,
      ellipsis: true,
    },
    {
      title: '出库单号',
      dataIndex: 'outordernumber',
      key: 'outordernumber',
      width: 120,
      ellipsis: true,
    },
    {
      title: '盘点单号',
      dataIndex: 'countordernumber',
      key: 'countordernumber',
      width: 120,
      ellipsis: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'proStatus',
      key: 'proStatus',
      width: 70,
      render: (status: number) => (
        <Tag color={status === 0 ? 'green' : 'red'}>
          {status === 0 ? '正常' : '异常'}
        </Tag>
      ),
    },
  ];

  // 查询数据
  const fetchData = async (params: QueryParams) => {
    setLoading(true);
    try {
      const queryParams = new URLSearchParams();
      queryParams.append('currentPage', params.currentPage.toString());
      queryParams.append('pageSize', params.pageSize.toString());
      
      if (params.team) queryParams.append('team', params.team);
      if (params.typeof) queryParams.append('typeof', params.typeof);
      if (params.warehouseName) queryParams.append('warehouseName', params.warehouseName);
      if (params.createTime) queryParams.append('createTime', params.createTime);
      if (params.endTime) queryParams.append('endTime', params.endTime);

      const response = await fetch(`http://localhost:5233/api/InandoutofStorage/QueryInandoutofStorage?${queryParams.toString()}`);
      const result: ApiResponse = await response.json();

      if (result.code === 200) {
        setDataSource(result.data.pageData || []);
        setTotal(result.data.totalCount || 0);
      } else {
        console.error('查询失败:', result.message);
      }
    } catch (error) {
      console.error('查询错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 搜索
  const onSearch = () => {
    const values = form.getFieldsValue();
    const params: QueryParams = {
      currentPage: 1,
      pageSize,
      team: values.team,
      typeof: values.typeof,
      warehouseName: values.warehouseName,
    };

    if (values.timeRange && values.timeRange.length === 2) {
      params.createTime = values.timeRange[0].format("YYYY-MM-DDTHH:mm:ss.SSSZ");
      params.endTime = values.timeRange[1].format("YYYY-MM-DDTHH:mm:ss.SSSZ");
    }

    setCurrentPage(1);
    fetchData(params);
  };

  // 重置
  const onReset = () => {
    form.resetFields();
    setCurrentPage(1);
    fetchData({ currentPage: 1, pageSize });
  };

  // 分页变化
  const onPageChange = (page: number, size?: number) => {
    const values = form.getFieldsValue();
    const params: QueryParams = {
      currentPage: page,
      pageSize: size || pageSize,
      team: values.team,
      typeof: values.typeof,
      warehouseName: values.warehouseName,
    };

    if (values.timeRange && values.timeRange.length === 2) {
      params.createTime = values.timeRange[0].format("YYYY-MM-DDTHH:mm:ss.SSSZ");
      params.endTime = values.timeRange[1].format("YYYY-MM-DDTHH:mm:ss.SSSZ");
    }

    setCurrentPage(page);
    if (size) setPageSize(size);
    fetchData(params);
  };

  // 页面加载时获取数据
  useEffect(() => {
    console.log("=== 查询页面初始化加载 ===");
    // 获取初始数据
    fetchData({ currentPage: 1, pageSize });
  }, []);

  // 监听路由变化，确保从添加页面跳转过来时刷新数据
  useEffect(() => {
    console.log("=== 路由变化检测 ===");
    console.log("当前路径:", location.pathname);
    
    if (location.pathname === '/InandoutofStorageQuery') {
      console.log("进入查询页面，刷新数据");
      fetchData({ currentPage: 1, pageSize });
      setCurrentPage(1);
    }
  }, [location.pathname, pageSize]);

  // 监听路由变化，当页面重新进入时刷新数据
  useEffect(() => {
    const handleVisibilityChange = () => {
      if (!document.hidden) {
        console.log("页面重新可见，刷新数据");
        // 页面变为可见时刷新数据
        fetchData({ currentPage: currentPage, pageSize });
      }
    };

    document.addEventListener('visibilitychange', handleVisibilityChange);
    
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, [currentPage, pageSize]);

  return (
    <div className={styles.container}>
      {/* 查询条件 */}
      <div className={styles.searchForm}>
        <Form
          form={form}
          layout="inline"
          onFinish={onSearch}
        >
          <Form.Item name="team" label="团队">
            <Select placeholder="团队" style={{ width: 150 }} allowClear>
              <Select.Option value="南京团队<>">南京团队</Select.Option>
              <Select.Option value="苏州1号团队<>">苏州1号团队</Select.Option>
              <Select.Option value="杭州团队<>">杭州团队</Select.Option>
              <Select.Option value="厦门团队<>">厦门团队</Select.Option>
              <Select.Option value="北京团队<>">北京团队</Select.Option>
              <Select.Option value="上海团队<>">上海团队</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item name="typeof" label="类型">
            <Select placeholder="类型" style={{ width: 120 }} allowClear>
              <Select.Option value="入库">入库</Select.Option>
              <Select.Option value="出库">出库</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item name="warehouseName" label="仓库名称">
            <Select placeholder="仓库名称" style={{ width: 150 }} allowClear>
              <Select.Option value="仓库A">仓库A</Select.Option>
              <Select.Option value="仓库B">仓库B</Select.Option>
              <Select.Option value="仓库C">仓库C</Select.Option>
              <Select.Option value="仓库D">仓库D</Select.Option>
              <Select.Option value="仓库E">仓库E</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item name="createTime" label="开始时间">
            <Input placeholder="开始时间" style={{ width: 180 }} />
          </Form.Item>

          <Form.Item name="endTime" label="结束时间">
            <Input placeholder="结束时间" style={{ width: 180 }} />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" className={styles.searchBtn}>
                搜索
              </Button>
              <Button onClick={onReset} className={styles.resetBtn}>
                重置
              </Button>
              <Button type="primary" className={styles.exportBtn}>
                导出数据到本地表格
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>

      {/* 数据表格 */}
      <div className={styles.tableContainer}>
        <Table
          columns={columns}
          dataSource={dataSource}
          loading={loading}
          rowKey="id"
          size="small"
          pagination={{
            current: currentPage,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100'],
            onChange: onPageChange,
            onShowSizeChange: onPageChange,
          }}
        />
      </div>
    </div>
  );
};

export default InandoutofStorageQuery;